#include "ExeInfoDatabase.h"
#include "SqliteWrapper.h"

ExeInfoDatabase::ExeInfoDatabase()
{

}


ExeInfoDatabase::~ExeInfoDatabase()
{
	ReleaseDBHandler();
}


ExeInfoDatabase* ExeInfoDatabase::GetInstance()
{
	static ExeInfoDatabase exeInfoDatabases;
	return &exeInfoDatabases;
}


bool ExeInfoDatabase::InsertData(std::string strFilePath, std::string strFileDescription, std::string strOriginalFilename)
{
	bool bRet = false;
	if (!strFilePath.empty())
	{
		std::string strSQL = "insert into EXE_INFO values(?, ?, ?);";

		if (strFileDescription.empty())
		{
			strFileDescription = "empty";
		}

		if (strOriginalFilename.empty())
		{
			strOriginalFilename = "empty";
		}

		SQLiteStatement *pStat = m_pSqliteWrapper->Statement(strSQL);
		if (pStat != NULL)
		{
			if (pStat->Bind(0, strFilePath))
			{
				if (pStat->Bind(1, strFileDescription))
				{
					if (pStat->Bind(2, strOriginalFilename))
					{
						if (pStat->Execute())
						{
							bRet = true;
						}
					}
				}
			}

			if (pStat != NULL)
			{
				delete pStat;
				pStat = NULL;
			}
		}
	}

	return bRet;
}


bool ExeInfoDatabase::InsertData(std::string& strSQL, DBItem& dbItem)
{
	bool bRet = false;
	SQLiteStatement *pStat = m_pSqliteWrapper->Statement(strSQL);
	if (pStat != NULL)
	{
		if (pStat->Bind(0, dbItem.strMD5))
		{
			if (pStat->Bind(1, dbItem.strOriginalFilename))
			{
				pStat->Bind(2, dbItem.strFileDescription);

				pStat->Bind(3, dbItem.strFileVersion);

				pStat->Bind(4, dbItem.strProductName);

				pStat->Bind(5, dbItem.strProductVersion);

				pStat->Bind(6, dbItem.strLegalCopyright);

				pStat->Bind(7, dbItem.strSigner);

				pStat->Bind(8, dbItem.strFilePath);

				if (pStat->Execute())
				{
					bRet = true;
				}				
			}
		}

		if (pStat != NULL)
		{
			delete pStat;
			pStat = NULL;
		}
	}

	return bRet;
}


bool ExeInfoDatabase::Initialize(const std::string& strDbPath)
{
	if (m_pSqliteWrapper == NULL)
	{
		m_pSqliteWrapper = new SQLiteWrapper();
		if (m_pSqliteWrapper == NULL)
		{
			return false;
		}
	}

	if (!m_pSqliteWrapper->Open(strDbPath))
	{
		ReleaseDBHandler();
		return false;
	}

	std::string strSQL = "CREATE TABLE IF NOT EXISTS EXE_INFO(FilePath text primary key not null, FileDescription text, OriginalFilename text);";
	if (!m_pSqliteWrapper->DirectStatement(strSQL))
	{
		ReleaseDBHandler();
		return false;
	}

	return true;
}



bool ExeInfoDatabase::Initialize(const std::string& strDbPath, const std::string& strSQL)
{
	if (m_pSqliteWrapper == NULL)
	{
		m_pSqliteWrapper = new SQLiteWrapper();
		if (m_pSqliteWrapper == NULL)
		{
			return false;
		}
	}

	if (!m_pSqliteWrapper->Open(strDbPath))
	{
		ReleaseDBHandler();
		return false;
	}

	if (!m_pSqliteWrapper->DirectStatement(strSQL))
	{
		ReleaseDBHandler();
		return false;
	}

	return true;
}



void ExeInfoDatabase::ReleaseDBHandler()
{
	if (NULL != m_pSqliteWrapper)
	{
		delete m_pSqliteWrapper;
		m_pSqliteWrapper = NULL;
	}
}


void ExeInfoDatabase::Close()
{

}